package com.dhecp.project.system.service.impl;

import com.alibaba.fastjson.JSON;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.dhecp.common.constant.Constants;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.framework.shiro.service.SysPasswordService;
import com.dhecp.framework.util.ShiroUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dhecp.project.system.domain.SysUserInfo;
import com.dhecp.project.system.mapper.SysUserInfoMapper;
import com.dhecp.project.system.service.SysUserInfoService;

/**
 * 用户 业务层处理
 * @author DH-Xxj
 */
@Service
public class SysUserInfoServiceImpl implements SysUserInfoService{
    private String moduleTable = "TS_USERINFO";
    private static final Logger log = LoggerFactory.getLogger(SysUserInfoServiceImpl.class);

    @Autowired
    private SysUserInfoMapper userInfoMapper;
    /**
     * 验证用户名和密码
     * @param params
     * @return UserInfo
     * @author DH-Xxj
     */
    @Override
    public SysUserInfo queryByUseridAndPass(String userId, String passWord) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userId", userId);
        params.put("userPassWord", passWord);
        return userInfoMapper.findByUserIdAndPass(params);
    }
    
    /**
     * 拓展用户登录验证
     * @param params
     * @return String (返回异常提示信息，返回空代表无异常)
     * @author DH-Xxj
     */
    @Override
    public String queryUserLoginException(Map<String, Object> params) {
    	return userInfoMapper.findUserLoginException(params);
    }

    /**
     * 通过用户编号查询用户信息
     * @param userId
     * @return 实体-UserInfo
     * @author DH-Xxj
     */
    @Override
    public SysUserInfo queryByUserId(String userId) {
        return userInfoMapper.findByUserId(userId);
    }

    /**
     * 按条件查询用户列表
     * @param params
     * @param nowherestr 若存在（任意值），表示不进行条件过滤
     * @param nodatascode 若存在（任意值），表示不进行数据权限控制
     * @return List-UserInfo
     * @author DH-Xxj
     * @throws Exception
     */
    @Override
    public List<SysUserInfo> queryUserList(Map<String, Object> params) throws Exception {
    	params.put("moduleTable", moduleTable);
        params.put("tablealias", "t1");	//查询表别名
  		if (params.get("field") == null || params.get("field") == ""){
  			String orderBy = "userId asc";
  			PageUtils.startPageOrder(orderBy);
  		}else if ("userleveltext".equals(params.get("field").toString().toLowerCase())){
  			String orderBy = "";
  			if (params.get("order") != null && "desc".equals(params.get("order").toString().toLowerCase())){
  	  			orderBy = "userLevel desc";
  			}else{
  	  			orderBy = "userLevel asc";
  	  		}
  			PageUtils.startPageOrder(orderBy);
  		}else{
  			PageUtils.startPage();	
  		}
        return userInfoMapper.findUserList(params);
    }

    /**
     * 通过用户编号或用户名称查询用户信息
     * @param params
     * @param params 必要参数：用户编号 或 用户名称
     * @return
     * @author DH-Xxj
     */
    @Override
    public List<SysUserInfo> queryUserListByUserIdOrUserName(Map<String, Object> params) {
        String userIdOrUserName = params.get("userIdOrUserName").toString();
  		if (params.get("field") == null || params.get("field") == ""){
  			String orderBy = "userId asc";
  			PageUtils.startPageOrder(orderBy);
  		}else{
  			PageUtils.startPage();	
  		}
        return userInfoMapper.findByUserIdOrUserName(userIdOrUserName);
    }

    /**
     * 新增用户信息
     * @param userInfoItems 对应实体类的json格式字符串
     * @return AjaxResult
     * @author DH-Xxj
     */
    @Override
    public AjaxResult insertUserInfo(Map<String, Object> params) {
        List<SysUserInfo> userInfoList = JSON.parseArray(params.get("userInfoItems").toString(), SysUserInfo.class);
        if (userInfoList == null || userInfoList.size() == 0) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
        SysPasswordService sysPasswordService = new SysPasswordService();
        for (SysUserInfo userInfo : userInfoList) {
            if (userInfoMapper.findByUserId(userInfo.getUserId()) != null){
                return AjaxResult.error("用户编号已经存在，不能重复添加！");
            }else{
            	//初始密码设置为用户编号
            	String newPassword = sysPasswordService.encryptPassword(userInfo.getUserId(), userInfo.getUserId(), Constants.PASSWORD_SALT);
            	userInfo.setUserPassWord(newPassword);
            	userInfoMapper.insert(userInfo);
            }
        }
        return AjaxResult.success("操作成功");
    }

    /**
     * 删除用户信息
     * @param userInfoItems 对应实体类的json格式字符串
     * @return AjaxResult
     * @author DH-Xxj
     */
    @Override
    public AjaxResult deleteUserInfo(Map<String, Object> params) {
        List<SysUserInfo> userInfoList = JSON.parseArray(params.get("userInfoItems").toString(), SysUserInfo.class);
        if (userInfoList == null || userInfoList.size() == 0) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
        for (SysUserInfo userInfo : userInfoList) {
            userInfoMapper.deleteUserByUserId(userInfo);
        }
        return AjaxResult.success("操作成功");
    }

    /**
     * 修改用户密码
     * @param upType 修改类型（"resetpwd":重置密码，无需提供原密码；"changepwd":修改密码，需要提供原密码）
     * @param userId 用户编号
     * @param newPwd 新用户密码
     * @param oldPwd 原用户密码，修改密码时需要提供，重置密码时可不提供
     * @return AjaxResult
     * @author DH-Xxj
     */
    @Override
    public AjaxResult updateUserPassWord(Map<String, Object> params){
        if (params.get("upType") == null || params.get("upType") == ""){
            return AjaxResult.error("缺少参数：upType【修改类型】！");
        }
        if (params.get("userId") == null || params.get("userId") == ""){
            return AjaxResult.error("缺少参数：userId【用户编号】！");
        }
        if (params.get("newPwd") == null || params.get("newPwd") == ""){
            return AjaxResult.error("缺少参数：newPwd【新用户密码】！");
        }
        String upType = params.get("upType").toString().toLowerCase();
        String userId = params.get("userId").toString();
        String newPwd = params.get("newPwd").toString();
        
        SysPasswordService sysPasswordService = new SysPasswordService();
        SysUserInfo userInfo = new SysUserInfo();
        SysUserInfo userInfoChecked = userInfoMapper.findByUserIdAndPass(params);
        if ("resetpwd".equals(upType)){ //重置密码，无需提供原密码,需要管理员才能重置
            int userLevel = ShiroUtils.getSysUser().getUserLevel();	//当前用户管理级别

        	if (userInfoChecked == null){
        		return AjaxResult.error("用户【" + userId + "】不存在！");
        	}else if (userLevel < 6){
        		return AjaxResult.error("只有管理员才能重置密码！您可以打开密码修改功能，验证原密码后进行修改或联系管理员重置密码！");
        	}else{
            	String newPassword = sysPasswordService.encryptPassword(userId, newPwd, Constants.PASSWORD_SALT);
            	userInfo.setUserPassWord(newPassword);
            	userInfo.setUserId(userId);
                userInfoMapper.updatePassWord(userInfo);
        	}
        }else if ("changepwd".equals(upType)){ //修改密码，需要提供原密码            
            if (params.get("oldPwd") == null || params.get("oldPwd") == ""){
                return AjaxResult.error("缺少参数：oldPwd【原用户密码】！");
            }
            String oldPwd = params.get("oldPwd").toString();
        	String oldPassword = sysPasswordService.encryptPassword(userId, oldPwd, Constants.PASSWORD_SALT);
            
        	if (userInfoChecked == null){
        		return AjaxResult.error("用户【" + userId + "】不存在！");
        	}else if (!userInfoChecked.getUserPassWord().toString().equals(oldPassword)){
        		return AjaxResult.error("用户【" + userId + "】的原始密码不正确，请重新输入！");
        	}else{
            	String newPassword = sysPasswordService.encryptPassword(userId, newPwd, Constants.PASSWORD_SALT);
            	userInfo.setUserPassWord(newPassword);
            	userInfo.setUserId(userId);
                userInfoMapper.updatePassWord(userInfo);
        	}        	
        }else{
            return AjaxResult.error("未知的修改类型[upType]！");
        }
    	return AjaxResult.success("操作成功");
    }

    /**
     * 修改用户信息
     * @param userInfoItems 对应实体类的json格式字符串
     * @param upType 修改类型（修改用户信息：upuser，修改用户基础信息：upuserbaseinfo，修改用户皮肤：upskin，修改档案照片：upuserphoto，修改用户头像：upuserpicture）
     * @return AjaxResult
     * @author DH-Xxj
     */
    @Override
    public AjaxResult updateUserInfo(Map<String, Object> params) {
        if (params.get("upType") == null || params.get("upType") == ""){
            return AjaxResult.error("缺少参数：upType【修改类型】！");
        }
        List<SysUserInfo> userInfoList = JSON.parseArray(params.get("userInfoItems").toString(), SysUserInfo.class);
        if (userInfoList == null || userInfoList.size() == 0) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
        if ("upuser".equals(params.get("upType").toString().toLowerCase())){
            for (SysUserInfo userInfo : userInfoList) {
                //修改用户信息
            	userInfo.setUpdateUser(ShiroUtils.getUserId());
            	userInfo.setUpdateTime(new Date());
                userInfoMapper.update(userInfo);
            }
        }else if ("upuserbaseinfo".equals(params.get("upType").toString().toLowerCase())){
            for (SysUserInfo userInfo : userInfoList) {
                //修改用户信息
            	userInfo.setUpdateUser(ShiroUtils.getUserId());
            	userInfo.setUpdateTime(new Date());
                userInfoMapper.updateUserBaseInfo(userInfo);
            }
        }else if ("upskin".equals(params.get("upType").toString().toLowerCase())){
            for (SysUserInfo userInfo : userInfoList) {
                //修改用户皮肤
                userInfoMapper.updateSkin(userInfo);
            }
        }else if ("upuserphoto".equals(params.get("upType").toString().toLowerCase())){
            for (SysUserInfo userInfo : userInfoList) {
                //修改档案照片
                userInfoMapper.updateUserPhoto(userInfo);
            }
        }else if ("upuserpicture".equals(params.get("upType").toString().toLowerCase())){
            for (SysUserInfo userInfo : userInfoList) {
                //修改用户头像
                userInfoMapper.updateUserPicture(userInfo);
            }
        }else{
            return AjaxResult.error("未知的修改类型[upType]！");
        }
        return AjaxResult.success("操作成功");
    }
}
